//
//  OpenDettaglioInterventoViewController.m
//  InterventixApp
//
//  Created by Diego Falcinelli on 04/06/13.
//
//

#import "OpenDettaglioInterventoViewController.h"
#import "TecniciDettaglioInterventoViewController.h"
#import "TipoDettaglioInterventoViewController.h"
#import "InizioDettaglioInterventoViewController.h"
#import "FineDettaglioInterventoViewController.h"
#import "NoteDettaglioViewController.h"

@interface OpenDettaglioInterventoViewController ()

@end

@implementation OpenDettaglioInterventoViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
	// Do any additional setup after loading the view.
    self.array = [NSMutableArray arrayWithCapacity:0];
    [self.array addObject:@"Tipo"];
    [self.array addObject:@"Oggetto"];
    [self.array addObject:@"Tecnici"];
    [self.array addObject:@"Descrizione"];
    [self.array addObject:@"Inizio"];
    [self.array addObject:@"Fine"];
    [self.array addObject:@"Totale"];
    
    self.back = false;
    self.remove = false;
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

-(IBAction) indietro{
    if(![self.coreDataManager checkDettaglio:self.dett_intervento]){
        if(self.nuovo){
            self.back = true;
            UIAlertView *myAlertView = [[UIAlertView alloc] initWithTitle:@"Dati Incompleti"
                                                                  message:@"Eliminare il nuovo dettaglio?" delegate:self cancelButtonTitle:@"Elimina" otherButtonTitles:@"Completa", nil];
            [myAlertView setAlertViewStyle:UIAlertViewStyleDefault];
            [myAlertView show];
        }else{
            self.back = true;
            UIAlertView *myAlertView = [[UIAlertView alloc] initWithTitle:@"Dati Incompleti"
                                                              message:@"Annullare le modifiche effettuate?" delegate:self cancelButtonTitle:@"Annulla" otherButtonTitles:@"Completa", nil];
            [myAlertView setAlertViewStyle:UIAlertViewStyleDefault];
            [myAlertView show];
        }
        
    }else{
        [[self navigationController] popViewControllerAnimated:YES];
        if(self.nuovo){
            [self.intervento addDettagliObject:self.dett_intervento];
        }
    }
}

-(IBAction) elimina{
    UIAlertView *myAlertView = [[UIAlertView alloc] initWithTitle:@"Attenzione"
                                                          message:@"Eliminare il dettaglio?" delegate:self cancelButtonTitle:@"Annulla" otherButtonTitles:@"Rimuovi", nil];
    [myAlertView setAlertViewStyle:UIAlertViewStyleDefault];
    [myAlertView show];
    self.remove = true;
}

- (void)viewDidAppear:(BOOL)animated{
    [self.table reloadData];
}

// TABELLA

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [self.array count];
}
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section{
    if([self.dett_intervento.iddettaglio intValue]<0)return @"Nuovo Dettaglio Intervento";
	return [NSString stringWithFormat: @"Dettaglio Intervento %@",self.dett_intervento.iddettaglio];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *CellIdentifier = @"Cell";
    
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier];
    [cell setBackgroundColor:[UIColor colorWithRed:1 green:1 blue:1 alpha:1]];
    
    NSString *name = [self.array objectAtIndex:indexPath.row];
    if([name isEqualToString:@"Tipo"] && self.dett_intervento.tipo != nil && ![self.dett_intervento.tipo isEqual:[NSNull null]]){
        cell.textLabel.text = name;
        cell.detailTextLabel.text = self.dett_intervento.tipo;
        cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
    }
    if([name isEqualToString:@"Oggetto"] && self.dett_intervento.oggetto != nil && ![self.dett_intervento.oggetto isEqual:[NSNull null]]){
        cell.textLabel.text = name;
        cell.detailTextLabel.text = self.dett_intervento.oggetto;
        cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
    }
    if([name isEqualToString:@"Tecnici"]){
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:CellIdentifier];
        cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
        [cell setBackgroundColor:[UIColor colorWithRed:1 green:1 blue:1 alpha:1]];
        cell.textLabel.text = name;
        cell.detailTextLabel.text = [NSString stringWithFormat:@"%d",[self.dett_intervento.tecnici count]];
    }
    if([name isEqualToString:@"Inizio"] && self.dett_intervento.inizio != nil && ![self.dett_intervento.inizio isEqual:[NSNull null]]){
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:CellIdentifier];
        [cell setBackgroundColor:[UIColor colorWithRed:0.8 green:0.8 blue:0.8 alpha:1]];
        NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
        [dateFormatter setDateFormat:@"dd/MM/yyyy HH:mm"];
        NSString *dateString = [dateFormatter stringFromDate:self.dett_intervento.inizio];
        cell.textLabel.text = name;
        cell.detailTextLabel.text = dateString;
        cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
    }
    if([name isEqualToString:@"Fine"] && self.dett_intervento.fine != nil && ![self.dett_intervento.fine isEqual:[NSNull null]]){
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:CellIdentifier];
        [cell setBackgroundColor:[UIColor colorWithRed:0.8 green:0.8 blue:0.8 alpha:1]];
        
        NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
        [dateFormatter setDateFormat:@"dd/MM/yyyy HH:mm"];
        NSString *dateString = [dateFormatter stringFromDate:self.dett_intervento.fine];
        cell.textLabel.text = name;
        cell.detailTextLabel.text = dateString;
        cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
    }
    if([name isEqualToString:@"Totale"]){
        
        cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:CellIdentifier];
        [cell setBackgroundColor:[UIColor colorWithRed:0.8 green:0.3 blue:0.3 alpha:1]];
        cell.textLabel.textColor = [UIColor colorWithRed:1 green:1 blue:1 alpha:1];
        cell.textLabel.font = [UIFont boldSystemFontOfSize:16];
        cell.textLabel.text = name;
        cell.detailTextLabel.textColor = [UIColor colorWithRed:1 green:1 blue:1 alpha:1];
        cell.detailTextLabel.font = [UIFont boldSystemFontOfSize:16];
        
        double num = [self.dett_intervento.fine timeIntervalSinceDate:self.dett_intervento.inizio]/60.00/60.00;
        int pint = (int) num;
        double pdec = num -pint;
        NSString *ss;
        if(pdec < 0.24)ss=[NSString stringWithFormat:@"%dh",pint];
        else if(pdec < 0.49)ss=[NSString stringWithFormat:@"%dh ¼",pint];
        else if(pdec < 0.74)ss=[NSString stringWithFormat:@"%dh ½",pint];
        else if(pdec < 0.99)ss=[NSString stringWithFormat:@"%dh ¾",pint];
        else ss=[NSString stringWithFormat:@"%dh",pint];
        
        cell.detailTextLabel.text = [NSString stringWithFormat:@"%@",ss];
        cell.accessoryType = UITableViewCellAccessoryNone;
    }
    if([name isEqualToString:@"Descrizione"]){
        cell.textLabel.text = name;
        cell.detailTextLabel.text = self.dett_intervento.descrizione;
        cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
    }
    else{
        cell.textLabel.text = name;
        cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
    }
    return cell;
}


// CellHeight
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
	return 50;
}

// CLICK
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSString *name = [self.array objectAtIndex:indexPath.row];
    self.nameSelect = name;
    
    if([name isEqualToString:@"Tecnici"]){
        TecniciDettaglioInterventoViewController *open = [self.storyboard instantiateViewControllerWithIdentifier:@"TecniciDettaglioInterventoViewController"];
        open.dett_intervento = self.dett_intervento;
        open.user = self.user;
        open.coreDataManager = self.coreDataManager;
        [self.navigationController pushViewController:open animated:TRUE];
    }
    if([name isEqualToString:@"Tipo"]){
        TipoDettaglioInterventoViewController *open = [self.storyboard instantiateViewControllerWithIdentifier:@"TipoDettaglioInterventoViewController"];
        open.dett_intervento = self.dett_intervento;
        open.user = self.user;
        open.coreDataManager = self.coreDataManager;
        [self.navigationController pushViewController:open animated:TRUE];
    }
    if([name isEqualToString:@"Fine"]){
        FineDettaglioInterventoViewController *open = [self.storyboard instantiateViewControllerWithIdentifier:@"FineDettaglioInterventoViewController"];
        open.dett_intervento = self.dett_intervento;
        open.user = self.user;
        open.coreDataManager = self.coreDataManager;
        [self.navigationController pushViewController:open animated:TRUE];
    }
    if([name isEqualToString:@"Inizio"]){
        InizioDettaglioInterventoViewController *open = [self.storyboard instantiateViewControllerWithIdentifier:@"InizioDettaglioInterventoViewController"];
        open.dett_intervento = self.dett_intervento;
        open.user = self.user;
        open.coreDataManager = self.coreDataManager;
        [self.navigationController pushViewController:open animated:TRUE];
    }
    if([name isEqualToString:@"Oggetto"]){
        UIAlertView *myAlertView = [[UIAlertView alloc] initWithTitle:@"Oggetto"
                                                              message:@"Oggetto del dettaglio dell'intervento" delegate:self cancelButtonTitle:@"Annulla" otherButtonTitles:@"Salva", nil];
        [myAlertView setAlertViewStyle:UIAlertViewStylePlainTextInput];
        [myAlertView textFieldAtIndex:0].font =[UIFont systemFontOfSize:12];
        if(![self.dett_intervento.oggetto isEqual:[NSNull null]] && self.dett_intervento.oggetto != nil){
            [myAlertView textFieldAtIndex:0].text = [NSString stringWithFormat:@"%@",self.dett_intervento.oggetto];
        }
        [myAlertView show];
    }
    
    if([name isEqualToString:@"Descrizione"]){
        /*UITextView *textView = [[UITextView alloc]initWithFrame:CGRectMake(12, 50, 260, 100)];
        [textView setText:self.dett_intervento.descrizione];
        
        UIAlertView *av = [[UIAlertView alloc]initWithTitle:@"Descrizione\n\n\n\n\n\n\n\n\n\n\n"
                                                    message:nil delegate:self cancelButtonTitle:@"Annulla" otherButtonTitles:@"Salva",nil];
        av.alertViewStyle = UIAlertViewStyleDefault;
        [av addSubview:textView];
        [av show];*/
        NoteDettaglioViewController *open = [self.storyboard instantiateViewControllerWithIdentifier:@"NoteDettaglioViewController"];
        open.dett_intervento = self.dett_intervento;
        open.coreDataManager= self.coreDataManager;
        
        [self.navigationController pushViewController:open animated:TRUE];
    }
}

-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
    if(buttonIndex == 0){
        if(self.back){
            if(self.nuovo){
                /*for(DettaglioIntervento *di in self.intervento.dettagli){
                    if([di.iddettagliointervento intValue] == [self.dett_intervento.iddettagliointervento intValue])
                    {
                        [self.intervento.dettagli delete:di];
                    }
                }*/
                [self.intervento removeDettagliObject:self.dett_intervento];
                [[self navigationController] popViewControllerAnimated:YES];
            }else{
                [self.intervento removeDettagliObject:self.dett_intervento];
                [self.intervento addDettagliObject:self.dett_intervento];
                
                [[self navigationController] popViewControllerAnimated:YES];
            }
        }
    }
    if (buttonIndex == 1){
        if(self.remove == true){
            [self.intervento removeDettagliObject:self.dett_intervento];
            [[self navigationController] popViewControllerAnimated:YES];
        }
        
        NSString *name = self.nameSelect;
        NSLog(@"%@",name);
        
        if([name isEqualToString:@"Oggetto"]){
            NSString *value = [[alertView textFieldAtIndex:0]text];
            self.dett_intervento.oggetto = value;
        }
        if([name isEqualToString:@"Descrizione"]){
            
            for(int i=0; i<alertView.subviews.count;i++){
                if ([[alertView.subviews objectAtIndex:i] isKindOfClass:[UITextView class]]) {
                    UITextView *tv = [alertView.subviews objectAtIndex:i];
                    self.dett_intervento.descrizione = tv.text;
                    NSLog(@"%@",tv.text);
                }
            }
            
        }
        
        [self.table reloadData];
    }
}


@end
